<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1400px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="质检方案编码" prop="schemeCode">
              <el-input v-model="formData.schemeCode" placeholder="请输入质检方案编码" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检方案名称" prop="schemeName">
              <el-input v-model="formData.schemeName" placeholder="请输入质检方案名称" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="formData.productId" placeholder="请选择产品" filterable remote reserve-keyword
                :remote-method="productRemoteMethod" :loading="productLoading" @change="handleProductSelect"
                style="width: 100%">
                <el-option v-for="product in productList" :key="product.id" :label="product.productName"
                  :value="product.id">
                  <span style="float: left">{{ product.productName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ product.productCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="formData.processId" placeholder="请选择工序" filterable remote reserve-keyword
                :remote-method="procedureRemoteMethod" :loading="procedureLoading" @change="handleProcedureSelect"
                style="width: 100%">
                <el-option v-for="procedure in procedureList" :key="procedure.id" :label="procedure.procedureName"
                  :value="procedure.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检方式" prop="schemeMethod">
              <el-select v-model="formData.schemeMethod" filterable placeholder="请选择质检方式" style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_METHOD)" :key="dict.value"
                  :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检类型" prop="schemeType">
              <el-select v-model="formData.schemeType" filterable placeholder="请选择质检类型" style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_TYPE)" :key="dict.value"
                  :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="巡检间隔(min)" prop="intervalTime">
              <el-input v-model="formData.intervalTime" placeholder="请输入巡检间隔(min)" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.schemeMethod == 2 || formData.schemeMethod == 3">
            <el-form-item :label="getSamplingLabel()" prop="samplingRatio"
              v-if="formData.schemeMethod == 2 || formData.schemeMethod == 3">
              <el-input v-model="formData.samplingRatio" :placeholder="getSamplingPlaceholder()" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value"
                  :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as InspectionSchemeApi from '@/api/quality/inspectionscheme';
import * as ProductBomApi from '@/api/basic/product/index.js';
import * as ProcedureApi from '@/api/basic/procedure';
import { getDictDatas, DICT_TYPE } from '@/utils/dict';

export default {
  name: "InspectionSchemeForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 产品列表
      productList: [],
      // 产品加载状态
      productLoading: false,
      // 工序列表
      procedureList: [],
      // 工序加载状态
      procedureLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        productId: undefined,
        productName: undefined,
        productCode: undefined,
        processId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        schemeCode: undefined,
        schemeName: undefined,
        schemeMethod: undefined,
        schemeType: undefined,
        intervalTime: undefined,
        samplingRatio: undefined,
        status: 1, // 默认开启状态
      },
      // 表单校验
      formRules: {
        schemeCode: [{ required: true, message: '质检方案编码不能为空', trigger: 'blur' }],
        schemeName: [{ required: true, message: '质检方案名称不能为空', trigger: 'blur' }],
        productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
        processId: [{ required: true, message: '工序不能为空', trigger: 'change' }],
        schemeMethod: [{ required: true, message: '质检方式不能为空', trigger: 'change' }],
        schemeType: [{ required: true, message: '质检类型不能为空', trigger: 'change' }],
        samplingRatio: [{ required: true, message: '抽检比例/数量不能为空', trigger: 'blur' }, { required: false }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
      },
    };
  },
  created() {
    // 进入页面默认加载20条产品数据
    this.getProductList();
    // 进入页面默认加载100条工序数据
    this.getProcedureList();
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await InspectionSchemeApi.getInspectionScheme(id);
          this.formData = res.data;
          this.dialogTitle = "编辑质检方案";
          // 使用产品名称调用远程搜索方法，确保产品选择器能正确显示当前产品
          if (this.formData.productName) {
            await this.productRemoteMethod(this.formData.productName);
          }
          // 使用工序名称调用远程搜索方法，确保工序选择器能正确显示当前工序
          if (this.formData.procedureName) {
            await this.procedureRemoteMethod(this.formData.procedureName);
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新建质检方案";
        this.formData.status = 1; // 新增时默认开启状态
      }
    },

    /** 获取工序列表 */
    async getProcedureList() {
      this.procedureLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100
        };
        const res = await ProcedureApi.getProcedurePage(params);
        this.procedureList = res.data.list || [];
      } catch (error) {
        console.error('获取工序列表失败:', error);
        this.procedureList = [];
      } finally {
        this.procedureLoading = false;
      }
    },

    /** 工序远程搜索方法 */
    async procedureRemoteMethod(query) {
      if (query) {
        this.procedureLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            procedureName: query // 根据工序名称搜索
          };
          const res = await ProcedureApi.getProcedurePage(params);
          this.procedureList = res.data.list || [];
        } catch (error) {
          console.error('搜索工序失败:', error);
          this.procedureList = [];
        } finally {
          this.procedureLoading = false;
        }
      } else {
        // 如果查询条件为空，默认显示前100条
        await this.getProcedureList();
      }
    },

    /** 工序选择后处理 */
    handleProcedureSelect() {
      if (this.formData.processId) {
        // 查找选中的工序信息
        const selectedProcedure = this.procedureList.find(p => p.id === this.formData.processId);
        if (selectedProcedure) {
          // 使用this.$set确保响应式更新
          this.formData.procedureCode = selectedProcedure.procedureCode;
          this.formData.procedureName = selectedProcedure.procedureName;
        }
      } else {
        // 如果取消选择，清空相关字段
        this.formData.procedureCode = undefined;
        this.formData.procedureName = undefined;
      }
    },

    /** 获取产品列表 */
    async getProductList() {
      this.productLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 20
        };
        const res = await ProductBomApi.getProductPage(params);
        this.productList = res.data.list;
      } catch (error) {
        console.error('获取产品列表失败:', error);
        this.productList = [];
      } finally {
        this.productLoading = false;
      }
    },

    /** 产品远程搜索方法 */
    async productRemoteMethod(query) {
      if (query) {
        this.productLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 20,
            productName: query // 根据产品名称搜索
          };
          const res = await ProductBomApi.getProductPage(params);
          this.productList = res.data.list;
        } catch (error) {
          console.error('搜索产品失败:', error);
          this.productList = [];
        } finally {
          this.productLoading = false;
        }
      } else {
        // 如果查询条件为空，默认显示前20条
        await this.getProductList();
      }
    },

    /** 产品选择后处理 */
    handleProductSelect() {
      if (this.formData.productId) {
        // 查找选中的产品信息
        const selectedProduct = this.productList.find(p => p.id === this.formData.productId);
        if (selectedProduct) {
          // 使用this.$set确保响应式更新
          this.formData.productName = selectedProduct.productName;
          this.formData.productCode = selectedProduct.productCode;
        }
      } else {
        // 如果取消选择，清空相关字段
        this.formData.productName = undefined;
        this.formData.productCode = undefined;
      }
    },

    /** 获取字典数据 */
    getDictDatas(dictType) {
      return this.$store.getters.dict_datas[dictType] || [];
    },

    /** 获取抽检比例/数量的标签 */
    getSamplingLabel() {
      if (this.formData.schemeMethod == '2') {
        return '抽检比例';
      } else if (this.formData.schemeMethod == '3') {
        return '抽检数量';
      }
      return '';
    },

    /** 获取抽检比例/数量的占位符 */
    getSamplingPlaceholder() {
      if (this.formData.schemeMethod === '2') {
        return '请输入抽检比例';
      } else if (this.formData.schemeMethod === '3') {
        return '请输入抽检数量';
      }
      return '';
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await InspectionSchemeApi.updateInspectionScheme(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await InspectionSchemeApi.createInspectionScheme(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        productId: undefined,
        productName: undefined,
        productCode: undefined,
        processId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        schemeCode: undefined,
        schemeName: undefined,
        schemeMethod: undefined,
        schemeType: undefined,
        intervalTime: undefined,
        samplingRatio: undefined,
        status: 1, // 重置时默认开启状态
      };
      this.resetForm("formRef");
    }
  }
};
</script>
